<template>
  <!-- 添加管理员 -->
  <h2>添加管理员:</h2>
  <el-form :model="admin" class="form-box">

    <el-form-item prop="adminname">
      <el-input v-model="admin.adminname" placeholder="姓名" />
    </el-form-item>
    <el-form-item prop="password">
      <el-input v-model="admin.password" placeholder="密码" />
    </el-form-item>
    <el-form-item>
      <el-select v-model="admin.role">
        <el-option value="1" label="超级管理员" />
        <el-option value="2" label="管理员" />
        <el-option value="3" label="轮播图维护员" />
        <el-option value="4" label="商品管理员" />
      </el-select>
    </el-form-item>

    <el-tree ref="treeRef" :data="data" show-checkbox default-expand-all node-key="id" highlight-current />

    <el-form-item>
      <el-button type="primary" @click="addAdmin()">添加</el-button>
      <el-button @click="cancelFn">取消</el-button>
    </el-form-item>

  </el-form>

</template>

<script setup lang="ts">

import type { IAdmin } from "@/myTypes";
import { reactive, ref } from "@vue/reactivity";
import { addAdminApi } from "@/api/admin.ts";
import type { AxiosResponse } from "axios";
import { ElMessage,ElTree } from "element-plus";
import {data} from "@/grants/data.ts"

interface IEmits {
  (e: 'cancel'): void,
  (e:"ok"):void
}

const emit = defineEmits<IEmits>()


// 定义管理员信息的数据
const admin = reactive<IAdmin>({
  adminname: "",
  password: "",
  role: "1",
  checkedKeys:[],
});

//定义权限相关的数据：

const treeRef = ref<InstanceType<typeof ElTree>>();


function addAdmin() {
  

  let arr = treeRef.value!.getCheckedKeys(false);
  treeRef.value!.getHalfCheckedKeys().forEach(item => {
    if(!arr.includes(item)){
      arr.push(item);
    }
  });


  console.log("arr",arr);
  
  admin.checkedKeys = arr;

  //发送请求：
  addAdminApi(admin)
    .then((res: AxiosResponse) => {
      if (res.data.code === "200") {
        ElMessage.success("添加成功！");
        emit("ok");
      } else if (res.data.code === "10004") {
        ElMessage.error("管理员已经存在");
      }
    })
}

function cancelFn(){
   emit("cancel");
}

</script>

<style>

</style>